﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 应收单服务插件
    /// </summary>
    /// <remarks>
    /// 功能：1.保存后获取销售出库单号，获取内部结算系数、内部结算含税单价、内部结算金额
    /// 2、保存后获取物料大类数据
    /// 创建人：lxl
    /// 创建日期：2024-06-14
    /// </remarks>
    [Description("应收单服务插件")]
    [Kingdee.BOS.Util.HotUpdate]
    public class RevOperatePlugin : AbstractOperationServicePlugIn
    {
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("AP_PAYABLEENTRY");//出库单号
            e.FieldKeys.Add("F_RDLV_OutBillNo");//出库单号
            e.FieldKeys.Add("FMATERIALID");//物料编码
            e.FieldKeys.Add("F_RDLV_MaterialGroup1");//物料编码
            e.FieldKeys.Add("F_RDLV_MaterialGroup2");//物料编码
            e.FieldKeys.Add("F_RDLV_MaterialGroup3");//物料编码
            e.FieldKeys.Add("F_RDLV_MtrlGroupNumber1");//物料编码
            e.FieldKeys.Add("F_RDLV_MtrlGroupNumber2");//物料编码
            e.FieldKeys.Add("F_RDLV_MtrlGroupNumber3");//物料编码
        }

        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            base.BeginOperationTransaction(e);
            if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Save)
            {
                //保存后插件
                foreach (DynamicObject o in e.DataEntitys)
                {
                    DynamicObjectCollection fEntity = o["AP_PAYABLEENTRY"] as DynamicObjectCollection;
                    foreach (var item in fEntity)
                    {
                        #region 获取结算数据
                        //获取出库单号
                        string fOutBillNo = Convert.ToString(item["F_RDLV_OUTBILLNO"]);
                        //物料编码
                        string FMATERIALNumber = Convert.ToString((item["MATERIALID"] as DynamicObject)?["number"] ?? "");
                        //获取金额
                        decimal NOTAXAMOUNT = Convert.ToDecimal(item["NOTAXAMOUNT"]);
                        string strSql = $@"select t2.F_RDLV_coefficient 结算系数,F_RDLV_settlement_price 结算单价含税
                      from T_SAL_OUTSTOCK t1 inner join 
                    T_SAL_OUTSTOCKENTRY t2 on t1.fid=t2.fid  join T_SAL_OUTSTOCKENTRY_f t3 on t2.fentryid=t3.fentryid
                    and fbillno='{fOutBillNo}'  inner join t_bd_material t4 on t2.FMATERIALID=t4.FMATERIALID and 
                    t4.fnumber='{FMATERIALNumber}'";
                        DynamicObjectCollection dd = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                        if (dd != null && dd.Count > 0)
                        {
                            //赋值数据
                            decimal F_QLTK_SettPriceRate = Convert.ToDecimal(dd[0]["结算系数"]);
                            decimal F_QLTK_SettTaxPrice = Convert.ToDecimal(dd[0]["结算单价含税"]);
                            //结算金额=内部结算系数*不含税金额
                            decimal F_QLTK_SettAmt = NOTAXAMOUNT * F_QLTK_SettPriceRate;
                            item["F_QLTK_SettPriceRate"] = F_QLTK_SettPriceRate;
                            item["F_QLTK_SettTaxPrice"] = F_QLTK_SettTaxPrice;
                            item["F_QLTK_SettAmt"] = F_QLTK_SettAmt;
                        }
                        #endregion
                        #region 获取物料大类数据
                        var fmaterid = item["MATERIALID"] as DynamicObject;//物料
                        string fgroupLevel1 = "", fgroupLevel2 = "", fgroupLevel3 = "", fgroupLevelNumber1 = "", fgroupLevelNumber2 = "", fgroupLevelNumber3 = "";

                        if (fmaterid != null)
                        {
                            string fmaterid_id = Convert.ToString(fmaterid["id"]);//物料id
                            strSql = $@"/*dialect*/with grouplevel as (select c.fname fgroup,b.fnumber,b.fparentid,1 as fgrouplevel from T_BD_MATERIAL a inner join 
                            T_BD_MATERIALGROUP b on  a.FMATERIALGROUP =b.FID and  a.fmaterialid={fmaterid_id}
                            inner join T_BD_MATERIALGROUP_l c on b.FID=c.fid 
                            union all select c.fname,b.fnumber,b.fparentid ,fgrouplevel+1 from grouplevel a inner join 
                            T_BD_MATERIALGROUP b on a.fparentid=b.FID  inner join T_BD_MATERIALGROUP_l c on b.FID=c.fid )
                             select fgroup,fnumber from grouplevel order by fgrouplevel desc  ";

                            DynamicObjectCollection getMtrlGarouObj = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                            // 遍历查询后结果，绑定界面
                            if (getMtrlGarouObj.Count == 3)
                            {
                                fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                                fgroupLevel2 = Convert.ToString(getMtrlGarouObj[1]["fgroup"]);//二级物料
                                fgroupLevel3 = Convert.ToString(getMtrlGarouObj[2]["fgroup"]);//三级物料
                                fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fnumber"]);//一级物料
                                fgroupLevelNumber2 = Convert.ToString(getMtrlGarouObj[1]["fnumber"]);//二级物料
                                fgroupLevelNumber3 = Convert.ToString(getMtrlGarouObj[2]["fnumber"]);//三级物料
                            }
                            else if (getMtrlGarouObj.Count == 2)
                            {
                                fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                                fgroupLevel2 = Convert.ToString(getMtrlGarouObj[1]["fgroup"]);//二级物料
                                fgroupLevel3 = "";//三级物料
                                fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fnumber"]);//一级物料
                                fgroupLevelNumber2 = Convert.ToString(getMtrlGarouObj[1]["fnumber"]);//二级物料
                                fgroupLevelNumber3 = "";
                            }

                            else if (getMtrlGarouObj.Count == 1)
                            {
                                fgroupLevel1 = Convert.ToString(getMtrlGarouObj[0]["fgroup"]);//一级物料
                                fgroupLevel2 = "";//二级物料
                                fgroupLevel3 = "";//三级物料
                                fgroupLevelNumber1 = Convert.ToString(getMtrlGarouObj[0]["fnumber"]);//一级物料
                                fgroupLevelNumber2 = "";//二级物料
                                fgroupLevelNumber3 = "";
                            }


                            else
                            {
                                fgroupLevel1 = "";//一级物料
                                fgroupLevel2 = "";//二级物料
                                fgroupLevel3 = "";//三级物料
                                fgroupLevelNumber1 = "";//一级物料
                                fgroupLevelNumber2 = "";//二级物料
                                fgroupLevelNumber3 = "";
                            }

                            item["F_RDLV_MaterialGroup1"] = fgroupLevel1;//1级物料
                            item["F_RDLV_MaterialGroup2"] = fgroupLevel2;//2级物料
                            item["F_RDLV_MaterialGroup3"] = fgroupLevel3;//3级物料
                            item["F_RDLV_MtrlGroupNumber1"] = fgroupLevelNumber1;//一级物料编码
                            item["F_RDLV_MtrlGroupNumber2"] = fgroupLevelNumber2;//2级物料编码
                            item["F_RDLV_MtrlGroupNumber3"] = fgroupLevelNumber3;//3级物料编码

                        }

                        #endregion

                    }


                }

            }
        }

    }
}
